﻿using NB.MGJ.Common.MVC;
using NB.MGJ.Model;
using NB.MGJ.Model.OriginsEntity;
using NB.MGJ.Service.Origins;
using NB.MGJ.Service.Product;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using NB.MGJ.Common.OSS;




namespace NB.MGJ.Web.Controllers
{
    public class OriginsMaterialController : BaseController
    {
        
        //
        // GET: /OriginsMaterial/
        private OriginsMaterialService _OriginsMaterialService;
        private OriginsModuleSEService _OriginsModuleSEService;
        private OriginsModuleService _OriginsModuleService;
        private OriginsNavService _OriginsNavService;
        private ProductBatchService _ProductBatchService;
   

        public  OriginsMaterialController()
        {
            _OriginsMaterialService=new OriginsMaterialService();
            _OriginsModuleSEService = new OriginsModuleSEService();
            _OriginsModuleService = new OriginsModuleService();
            _OriginsNavService = new OriginsNavService();
            _ProductBatchService = new ProductBatchService();
        }



        public ActionResult OriginsMaterialList()
        {

           var moduleList=GetMaterialInfo(967);
            return View();
        }
        public JsonResult PageList(string where, int pageIndex = 1, int pageSize = 10)
        {

             
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;

            if (!string.IsNullOrEmpty(where))
            {
                if (where.IndexOf("templet") != -1)
                {
                    pm.StrCondition=" MaterialId in (1,2,3,4,5) ";
                }
                else
                {
                    pm.StrCondition = " MaterialName like '%" + where + "%' ";
                }
            }
            var List = _OriginsMaterialService.GetPageList(ref pm,where,LogOnUser.EnterpriseId);
			return Json(List, JsonRequestBehavior.AllowGet);
        }


        public ActionResult ExperienceCenter()
        {
            return View();
        }




		/// <summary>
		/// 删除数据
		/// </summary>
		/// <param name="pageIndex"></param>
		/// <param name="pageSize"></param>
		/// <returns></returns>
		public int DelMaterial(int id) {
			int result = _OriginsMaterialService.DelMaterialService(id);
			return result;
		}
		
          
        public ActionResult GetMaterialList (string where,int pageIndex=1, int pageSize=10)
        {
            if (pageIndex == 0)
            {
                pageIndex++;
            }
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
		
            pm.StrCondition = " EnterpriseId="+LogOnUser.EnterpriseId;
			var List = _OriginsMaterialService.GetPageList(ref pm,where,LogOnUser.EnterpriseId);

            Hashtable ht = new Hashtable();

            ht.Add("data", List.PageData);
            ht.Add("total", List.TotalItemCount);
            return Json(ht, JsonRequestBehavior.AllowGet);

        }

        public ActionResult GetModuletList(int MaterialId, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex == 0)
            {
                pageIndex++;
            }
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.StrCondition = " MaterialId=" + MaterialId + " and ViewDel=0 ";
            var List = _OriginsModuleService.GetPageList(ref pm);
            Hashtable ht = new Hashtable();
            ht.Add("data", List.PageData);
            ht.Add("total", List.TotalItemCount);
            return Json(ht, JsonRequestBehavior.AllowGet);

        }


        public ActionResult AddOriginsMaterial()
        {
            return View();
        }

        public ActionResult EditOriginsMaterial(int materialId=0,int batchId=0)
        {


            var errorMsg = "";
            if (materialId == 0)
            {
                errorMsg = "请检查批次是否绑定素材！";
                return RedirectToAction("OriginsErrorPage","MaterialPreview", new
                {
                    errorMsg=errorMsg
                });
            }
            var model = _OriginsMaterialService.GetModel(materialId);
            if (model == null)
            {
                errorMsg = "素材不存在，请确定该素材是否删除";
                return RedirectToAction("OriginsErrorPage", "MaterialPreview", new
                {
                    errorMsg = errorMsg
                });
            }
            else
            {
                var batchModel = _ProductBatchService.GetModelById(batchId);
                if (batchModel != null)
                {
                    model.ProductBatch = batchId;
                    model.ProductId = batchModel.ProductId.ToString();
                }

        
                
            }


            switch (model.MaterialType)
            {
                case 0:
                    return RedirectToAction("StandardEdition", model);
                case 1:
                    return RedirectToAction("GoldEdtion", model);
                case 2:
                    return RedirectToAction("PlatinumEdtion", model);
                case 3:
                        return RedirectToAction("DiamondEdition", model);
                default:
                    break;
            }

            return null;
        }


        public ActionResult DiamondEdition(Origins_Material model)
        {

            //如果钻石版的认证导航模块不存在（即为0，则新建并绑定一个认证导航模块）
            //if (model.ModuleId == 0)
            //{
            //    Origins_Module ModuleModel = new Origins_Module();
            //    model.ChangeDate = DateTime.Now;
            //    var result = _OriginsModuleService.Add(ModuleModel);
            //    if (result > 0)
            //    {
            //        model.ModuleId = result;
            //    }
            //    _OriginsMaterialService.Update(model);
            //}

            ////获取权限认证导航列表
            //var authNavList = _OriginsNavService.GetNavAllByModuleId(model.ModuleId);
            ////获取模块列表
            //var moduleList = _OriginsModuleService.GetModuleAllByMaterialId(model.MaterialId);


            //ViewBag.materialModel = model;
            //ViewBag.authNavList = authNavList;
            //ViewBag.moduleList = moduleList;


            ViewBag.MaterialModel = model;
            return View();



        }




        public List<Origins_Material> GetOriginsTempletList ()
        {

          var list=_OriginsMaterialService.GetOriginsTempletList();

          return list;
        }


        public List<Origins_Module> GetMaterialInfo (int materialId)
        {

           //var list=GetOriginsTempletList();

           //var materialModel=_OriginsMaterialService.GetModel(materialId);

           var moduleList=_OriginsModuleService.GetModuleAllByMaterialId(materialId);

           foreach (var item in moduleList)
           {
               var navList=_OriginsNavService.GetNavAllByModuleId(item.ModuleId);
               if (navList.Count > 0)
               {
                 item.NavList=navList;
               }
             
           }

           return moduleList;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="fromMaterialId">模板素材ID</param>
        /// <param name="toMaterialId">空素材ID</param>
        /// <returns></returns>
        public ActionResult CopyMaterial (int fromMaterialId, int toMaterialId)
        {

            try
            {
                var moduleList = GetMaterialInfo(fromMaterialId);
                foreach (var item in moduleList)
                {
                    var moduleModel = new Origins_Module()
                    {
                        MaterialId = toMaterialId,
                        ChangeDate = DateTime.Now,
                        ChangeLoginID = LogOnUser.UserID,
                        ChangeLoginName = LogOnUser.RealName,
                        ModuleType = item.ModuleType,
                        NavStyle = item.NavStyle,
                        Remark = item.Remark,
                        IsHide = item.IsHide,
                        IsHideTitle = item.IsHideTitle,
                        Sort = item.Sort,
                        Title = item.Title,
                        ViewDel = item.ViewDel,
                        ModuleContent = item.ModuleContent
                    };
                    var navModuleId = _OriginsModuleService.Add(moduleModel);

                    if (item.NavList != null)
                    {
                        foreach (var innerItem in item.NavList)
                        {
                            var navModel = new Origins_Nav()
                            {
                                ModuleId = navModuleId,
                                NavName = innerItem.NavName,
                                Remark = innerItem.Remark,
                                Ico = innerItem.Ico,
                                Action = innerItem.Action

                            };

                            _OriginsNavService.Add(navModel);
                        }
                    }

                }

                return Json("1");
            }
            catch (Exception ex)
            {
                throw ex;
            }
         
        }



        public ActionResult AddExample(int materialId)
        {

            var qywhContent = @"<p><img src='http://avrilbucket.oss-cn-beijing.aliyuncs.com/qywh.jpg' title='qywh.jpg' alt='qywh.jpg'></p><p><span style='font-size: 12px;'>十多年的发展历程，公司始终坚持“创新，品质，服务，节约，敬业，感恩”12字理念。吸收新创意，严把质量关口，全方位的服务跟踪，坚持做出高品质产品。本着“追求、员工、技术、精神、利益”10字宗旨。现拥有一批精干的管理人员和一支高素质的专业技术队伍，舒适优雅的办公环境和拥有60多亩的全新现代化标准厂房。我们以质量为生命、时间为信誉、价格为竞争力的经营信念，立足于珠江三角洲</span></p>";


            var cptpContent = @"<p><img src='http://avrilbucket.oss-cn-beijing.aliyuncs.com/dm001.png' title='dm001.png' alt='dm001.png'></p>";


           


            var moduleModel = new Origins_Module()
            {
                MaterialId=materialId,
                ChangeDate=DateTime.Now,
                ChangeLoginID=LogOnUser.UserID,
                ChangeLoginName=LogOnUser.RealName,
                ModuleType=0,
                NavStyle=3,
                Remark=" this is word and picture ",
                IsHide=0,
                IsHideTitle=0,
                Sort=1,
                Title="产品图片",
                ViewDel=0,
                ModuleContent = cptpContent
                
            };

            _OriginsModuleService.Add(moduleModel);

            var moduleModel2 = new Origins_Module()
            {
                MaterialId = materialId,
                ChangeDate = DateTime.Now,
                ChangeLoginID = LogOnUser.UserID,
                ChangeLoginName = LogOnUser.RealName,
                ModuleType = 0,
                NavStyle = 3,
                Remark = " this is word and picture ",
                IsHide = 0,
                IsHideTitle = 0,
                Sort = 3,
                Title = "企业文化",
                ViewDel = 0,
                ModuleContent = qywhContent

            };


          var result=  _OriginsModuleService.Add(moduleModel2);


          var moduleModel3 = new Origins_Module()
          {
              MaterialId = materialId,
              ChangeDate = DateTime.Now,
              ChangeLoginID = LogOnUser.UserID,
              ChangeLoginName = LogOnUser.RealName,
              ModuleType = 2,
              NavStyle = 3,
              Remark = " this is cpxxtable ",
              IsHide = 0,
              IsHideTitle = 0,
              Sort = 2,
              Title = "产品户口本",
              ViewDel = 0,
              //ModuleContent = ""

          };


             _OriginsModuleService.Add(moduleModel3);


             var moduleModel4 = new Origins_Module()
             {
                 MaterialId = materialId,
                 ChangeDate = DateTime.Now,
                 ChangeLoginID = LogOnUser.UserID,
                 ChangeLoginName = LogOnUser.RealName,
                 ModuleType = 1,
                 NavStyle = 3,
                 Remark = " this is cpxxtable ",
                 IsHide = 0,
                 IsHideTitle = 0,
                 Sort = 2,
                 Title = "溯源档案",
                 ViewDel = 0,
                 ModuleContent = ""

             };


            var navModuleId= _OriginsModuleService.Add(moduleModel4);

             var navModel1 = new Origins_Nav()
             {
                 ModuleId=navModuleId,
                 NavName="生产流程",
                 Remark="这是生产流程，跳转到绑定的流程页面",
                 Ico = "/Content/webImgs/TraceSource/Ico/qcsy_qycj.png",
                 Action=3
             };

             var navModel2 = new Origins_Nav()
             {
                 ModuleId = navModuleId,
                 NavName = "质检报告",
                 Remark = "这是质检报告，跳转到绑定的质检报告页面",
                 Ico = "/Content/webImgs/TraceSource/Ico/qcsy_sclc.png",
                 Action=4

             };

             var navModel3 = new Origins_Nav()
             {
                 ModuleId = navModuleId,
                 NavName = "企业荣誉",
                 Remark = "这是生产流程，跳转到绑定的企业荣誉页面",
                 Ico = "/Content/webImgs/TraceSource/Ico/qcsy_zzlc.png",
                 Action=5

             };

             _OriginsNavService.Add(navModel1);
             _OriginsNavService.Add(navModel2);
             _OriginsNavService.Add(navModel3);



          return Json(result);
        }





        public ActionResult GetMaterialModelByMaterialId(int materialId)
        {
            var materialModel = _OriginsMaterialService.GetModel(materialId);
            return Json(materialModel);
        }


        public ActionResult GetModuleListByMaterialId(int materialId)
        {
            var moduleList = _OriginsModuleService.GetModuleAllByMaterialId(materialId);
            return Json(moduleList);
        }



        public ActionResult GetDiamonExampleModuleList()
        {


            return Json("00");
        }



        public ActionResult StandardEdition(Origins_Material model)
        {
            var moduleSEModel = _OriginsModuleSEService.GetModel(model.ModuleId);

            ViewBag.materialModel = model;
            ViewBag.moduleSEModel = moduleSEModel;


            Dictionary<string, string> exDic = new Dictionary<string, string>();
            if (moduleSEModel.ExtendInfo != null)
            {
                exDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(moduleSEModel.ExtendInfo);
            }

            ViewBag.exDic = exDic;
            return View();
        }

        public ActionResult GoldEdtion(Origins_Material model)
        {
            var moduleSEModel = _OriginsModuleSEService.GetModel(model.ModuleId);

            ViewBag.materialModel = model;
            ViewBag.moduleSEModel = moduleSEModel;

            Dictionary<string, string> exdic = new Dictionary<string, string>();
            var flowList = new List<FlowSEModel>();
            if (!string.IsNullOrEmpty(moduleSEModel.ExtendInfo))
            {
                exdic = JsonConvert.DeserializeObject<Dictionary<string, string>>(moduleSEModel.ExtendInfo);
            }
            if (!string.IsNullOrEmpty(moduleSEModel.Flow))
            {
                flowList = JsonConvert.DeserializeObject<List<FlowSEModel>>(moduleSEModel.Flow);
            }


            ViewBag.exDic = exdic;
            ViewBag.flowList = flowList;  
            return View();
        }

        public ActionResult PlatinumEdtion(Origins_Material model)
        {
            return View();
        }



        public ActionResult NavEdit(int navId)
        {
            ViewBag.navId = navId;
            return View();
        }

        public ActionResult NavSave(Origins_Nav model)
        {
          

            if (model.NavId == 0)
            {
                model.ChangeDate = DateTime.Now;
                model.ChangeLoginID = LogOnUser.UserID;
                model.ChangeLoginName = LogOnUser.LoginName;
                model.ViewDel = 0;

                var result = _OriginsNavService.Add(model);
                model.NavId = result;
                Hashtable ht = new Hashtable();
                ht.Add("type", "add");
                ht.Add("navEntity", model);
                ht.Add("result", result);
                return Json(ht);
            }
            else
            {

                model.ChangeDate = DateTime.Now;
                model.ChangeLoginID = LogOnUser.UserID;
                model.ChangeLoginName = LogOnUser.LoginName;

                var result = _OriginsNavService.Update(model);

                Hashtable ht = new Hashtable();
                ht.Add("type", "edit");
                ht.Add("navEntity", model);
                ht.Add("result", result);

                return Json(ht);
            }
        }


        public ActionResult SelectModuleList(int materialId)
        {
            ViewBag.MaterialId = materialId;
            return View();
        }


        //public ActionResult GetModuleListByMaterialId(int materialId)
        //{
        //    var result = _OriginsModuleService.GetModuleAllByMaterialId(materialId);
        //    return Json(result);
        //}

        public ActionResult GetMaterialListByEID(int EID)
        {
            var result = _OriginsMaterialService.GetMatetialListByEID(EID);
            return Json(result);
        }


        public ActionResult SelectMaterialList()
        {
            ViewBag.EID = LogOnUser.EnterpriseId;
            return View();
        }


        public ActionResult SelectTitleStyle()
        {
            return View();
        }


        public ActionResult MaterialSave(HttpPostedFileBase file, Origins_Material model)
        {
			int result = 0;

			model.ChangeDate = DateTime.Now;
			model.ChangeLoginID = LogOnUser.UserID;
			model.ChangeLoginName = LogOnUser.LoginName;

            model.EnterpriseId = LogOnUser.EnterpriseId;
            model.Category = 0;
            model.ViewDel = 0;

			if (model.MaterialId==0||model.MaterialId==null)
			{
                MaterialFactor mf = new MaterialFactor(LogOnUser);
				result=  mf.Create(model);
			}
			else
			{
				result = _OriginsMaterialService.Update(model);
			}
            return Json(result, JsonRequestBehavior.AllowGet);
			
        }

        public ActionResult UpdateMaterialName(string materialName, int materialId)
        {
            var materialModel = _OriginsMaterialService.GetModel(materialId);
            materialModel.MaterialName = materialName;
            var result=_OriginsMaterialService.Update(materialModel);
            return Json(result);
        }





        public ActionResult ModuleSave(Origins_Module model) 
		{		
            model.ChangeDate = DateTime.Now;
            model.ChangeLoginID = LogOnUser.UserID;
            model.ChangeLoginName = LogOnUser.LoginName;

            if (model.ModuleId == 0)
            {
                model.ViewDel = 0;

                var result = _OriginsModuleService.Add(model);
                return Json(result);
            }
            else
            {
                var result = _OriginsModuleService.Update(model);
                return Json(result);
            }
        }


          [ValidateInput(false)]
        public ActionResult ModuleSESave(Origins_ModuleSE model)
        {
            var re = System.Web.HttpContext.Current.Request;
            string fileName = string.Empty;

            string filePath = "";

            HttpPostedFile postedFile = re.Files["Picture"];
            if (postedFile.ContentLength > 0 && postedFile.ContentLength != 945)
            {
                 string name = DateTime.Now.ToString("yyyyMMddhhmmss");
                 fileName = name+System.IO.Path.GetFileName(postedFile.FileName);
                
                 var stream = postedFile.InputStream;
                 OssManager.Instance.PutObject(fileName, stream);
                 filePath = OssManager.Instance.GetUrl(fileName);
            }

            var oModuleSEModel = _OriginsModuleSEService.GetModel(model.ModuleId);

            if (filePath != "")
            {
                oModuleSEModel.Picture = filePath;
            }
            oModuleSEModel.ProductName = model.ProductName;
            oModuleSEModel.ProductCode = model.ProductCode;
            oModuleSEModel.ProduceArea = model.ProduceArea;
            oModuleSEModel.Format = model.Format;
            oModuleSEModel.ExtendInfo = model.ExtendInfo;
            oModuleSEModel.Flow = model.Flow;
            oModuleSEModel.ShortDescription = model.ShortDescription;

            _OriginsModuleSEService.Update(oModuleSEModel);
            return Json(model.ProductName);
        }

        








        public ActionResult GetModuelById(int id)
        {
            var ModuleModel = _OriginsModuleService.GetModel(id);
            return Json(ModuleModel);
        }



        public ActionResult GetNavListByModuleId(int id)
        {
            var navList = _OriginsNavService.GetNavAllByModuleId(id);
            return Json(navList);
        }


        public ActionResult GetNavModel(int id)
        {
            var navModel = _OriginsNavService.GetModel(id);
            return Json(navModel);
        }


        public ActionResult NavDelete(int id)
        {
            var result = _OriginsNavService.Del(id);
            return Json(result);
        }

        public ActionResult SortModule(List<int> json)
        {
            var result = _OriginsModuleService.SortModule(json);
            return Json(result);
        }





        public ActionResult ModuleDelete(int id)
        {
            var result = _OriginsModuleService.Del(id);
            return Json(result);
        }


        //public ActionResult Upload()
        //{
        //    string fileName = string.Empty;
        //    string result = string.Empty;

        //    HttpFileCollectionBase files = HttpContext.Request.Files;
        //    if (files.Count > 0)
        //    {
        //        HttpPostedFileBase postedFile = files[0];
        //        string fileNames = System.IO.Path.GetFileName(postedFile.FileName);
        //        if (!string.IsNullOrEmpty(fileNames))
        //        {
        //            string name = DateTime.Now.ToString("yyyyMMddhhmmss");
        //            if (!Directory.Exists(Server.MapPath(destPath)))
        //            {
        //                Directory.CreateDirectory(Server.MapPath(destPath));
        //            }
        //            fileName = destPath + name + "-" + fileNames;
        //            filePath = fileName;
        //            var paths = Server.MapPath(fileName);
        //            postedFile.SaveAs(paths);
        //            result = "上传成功。" + fileName;

        //        }
        //        else
        //        {
        //            result = "请选择文件。";
        //        }
        //    }
        //    else
        //    {
        //        result = "请选择文件。";

        //    }
        //    return Content(result);
        //}

        public ActionResult Upload()
        {
            HttpFileCollectionBase files = HttpContext.Request.Files;
            string result = string.Empty;
            string filePath = string.Empty;
            string fileName = string.Empty;

            if (files.Count > 0)
            {
                HttpPostedFileBase postedFile = files[0];
                 //fileName =System.Guid.NewGuid().ToString()+System.IO.Path.GetFileName(postedFile.FileName);

                fileName = System.Guid.NewGuid().ToString();

                if (!string.IsNullOrEmpty(fileName))
                {
                    var stream = postedFile.InputStream;
                    OssManager.Instance.PutObject(fileName, stream);
                    filePath = OssManager.Instance.GetUrl(fileName);
                    result = "上传成功。" + filePath;
                }
                else
                {
                    result = "请选择文件。";
                }
            }
            else
            {
                result = "请选择文件。";
            }
            return Content(result);
        }



        #region  临时枚举

        public ActionResult GetEnumJson(string name)
        {

            List<EnumModel> list = new List<EnumModel>();

            if (name == "isHide")
            {
                list.Add(new EnumModel
                {
                    id = Convert.ToInt32(0),
                    text = Convert.ToString("显示")
                });

                list.Add(new EnumModel
                {
                    id = Convert.ToInt32(1),
                    text = Convert.ToString("隐藏")
                });
            }
            if (name == "navAction")
            {
                list.Add(new EnumModel
                {
                    id = Convert.ToInt32(0),
                    text = Convert.ToString("链接")
                });

                list.Add(new EnumModel
                {
                    id = Convert.ToInt32(1),
                    text = Convert.ToString("模块")
                });

                list.Add(new EnumModel
                {
                    id = Convert.ToInt32(2),
                    text = Convert.ToString("素材")
                });

                list.Add(new EnumModel
                {
                    id = Convert.ToInt32(3),
                    text = Convert.ToString("流程")
                });
            }
            if (name == "navStyle")
            {
                list.Add(new EnumModel
                {
                    id = Convert.ToInt32(0),
                    text = Convert.ToString("一行一项")
                });

                list.Add(new EnumModel
                {
                    id = Convert.ToInt32(1),
                    text = Convert.ToString("一行两项")
                });

                list.Add(new EnumModel
                {
                    id = Convert.ToInt32(2),
                    text = Convert.ToString("一行三项")
                });

                list.Add(new EnumModel
                {
                    id = Convert.ToInt32(3),
                    text = Convert.ToString("智能排序")
                });
            }


            return Json(list,JsonRequestBehavior.AllowGet);
        }







        #endregion

    }

    #region
    public class EnumModel
    {
        public int id
        {
            get;
            set;
        }
        public string text
        {
            get;
            set;
        }
    }
    #endregion



}